package com.example.administrator.liveapp.fragment;


import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.BookingDetailsPage;
import com.example.administrator.liveapp.activity.BookingListPage;
import com.example.administrator.liveapp.activity.LiveDetailsPage;
import com.example.administrator.liveapp.activity.LiveListPage;
import com.example.administrator.liveapp.activity.LoginPage;
import com.example.administrator.liveapp.activity.WxLoginPage;
import com.example.administrator.liveapp.adapter.LiveFragmentAdapter;
import com.example.administrator.liveapp.adapter.LiveFragmentAdapter2;
import com.example.administrator.liveapp.base.BaseFragment;
import com.example.administrator.liveapp.bean.LiveHomePageBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.GlideImageLoader;
import com.example.administrator.liveapp.view.FullyGridLayoutManager;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 以前直播Fragment(已经没有用了)
 */
public class LiveFragment extends BaseFragment {
    /**
     * 标题栏布局
     */
    private RelativeLayout title_bar;
    /**
     * 标题栏标题
     */
    private TextView title_bar_text;

    private View view;
    private Banner banner;
    private String[] cateid;//区分轮播图跳转页面
    private String[] id;//轮播图对应的跳转页面id
    private int[] timeStatus;//轮播图对应的跳转页面活动状态
    private List<String> images;
    private List<String> titles;
    private RecyclerView live_recycler_view;
    private RecyclerView live_recycler_view2;
    private FullyGridLayoutManager mGridLayoutManager, mGridLayoutManager2;
    private LiveFragmentAdapter liveFragmentAdapter;
    private LiveFragmentAdapter2 liveFragmentAdapter2;
    private RadioButton livePage_more, livePage2_more;
    private LiveHomePageBean bean;
    /**
     * 下拉刷新
     */
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;
    private View loadView;//loding页面（加载页）

    @Override
    protected View initView() {
        view = View.inflate(mContext, R.layout.livefragment_layout, null);
        title_bar = (RelativeLayout) view.findViewById(R.id.title_bar);
        title_bar_text = (TextView) view.findViewById(R.id.title_bar_text);

        loadView = view.findViewById(R.id.loadView);
        banner = (Banner) view.findViewById(R.id.banner_two);
        live_recycler_view = (RecyclerView) view.findViewById(R.id.live_recycler_view);
        live_recycler_view2 = (RecyclerView) view.findViewById(R.id.live_recycler_view2);
        livePage_more = (RadioButton) view.findViewById(R.id.livePage_more);
        livePage2_more = (RadioButton) view.findViewById(R.id.livePage2_more);

        /**
         * 下拉刷新
         */
        mRefreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        setThemeColor(R.color.colorPrimary);
        if (isFirstEnter) {
            initData();
            isFirstEnter = false;
//            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
        return view;
    }

    private void setThemeColor(int colorPrimary) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.holo_blue_dark);
        //改变手机状态栏背景色
//        if (Build.VERSION.SDK_INT >= 21) {
//            getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getActivity(), colorPrimaryDark));
//        }
    }

    @Override
    protected void initData() {
        super.initData();
        String url = AppUrl.URL + AppUrl.ActivityHomeURL;
        XUtils.Get(url, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result, LiveHomePageBean.class);
                cateid = new String[bean.getBanner().size()];
                id = new String[bean.getBanner().size()];
                timeStatus = new int[bean.getBanner().size()];
                images = new ArrayList<>();
                titles = new ArrayList<>();
                if (bean.getBanner() != null) {
                    for (int i = 0; i < bean.getBanner().size(); i++) {
                        //ViewPager数据源
                        String imageUrl = (bean.getBanner().get(i).getImgurl());
                        cateid[i] = bean.getBanner().get(i).getCateid();
                        id[i] = bean.getBanner().get(i).getTypeid();
                        timeStatus[i] = bean.getBanner().get(i).getTimeStatus();
                        images.add(AppUrl.URL + imageUrl.substring(1, imageUrl.indexOf("|")));
                        titles.add(bean.getBanner().get(i).getBannertitle());
                    }
                }
                recyclerView();
                recyclerView2();
                banner();
                /**
                 * 标题栏
                 */
                title_bar.setVisibility(View.VISIBLE);
                title_bar_text.setText("活动");
                loadView.setVisibility(View.GONE);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
//                Toast.makeText(getContext(),ex.getMessage()+"网络请求失败",Toast.LENGTH_SHORT).show();
            }
        });
        Onclick();
    }

    private void Onclick() {
        livePage_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(mContext, LiveListPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        livePage2_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(mContext, BookingListPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //底部加载
            }

            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                //下拉刷新
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                        refreshlayout.finishRefresh();
                    }
                }, 2000);
            }
        });
    }

    private void recyclerView() {
        //创建默认的GridLayoutManager
        mGridLayoutManager = new FullyGridLayoutManager(getContext(), 2);
        mGridLayoutManager.setScrollEnabled(false);
        live_recycler_view.setLayoutManager(mGridLayoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        live_recycler_view.setHasFixedSize(true);
        //创建并设置Adapter
        liveFragmentAdapter = new LiveFragmentAdapter(bean.getVideo());
        live_recycler_view.setAdapter(liveFragmentAdapter);
        liveFragmentAdapter.setOnItemClickListener(new LiveFragmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.putExtra("videoId", bean.getVideo().get(position).getVideoid());
                intent.setClass(mContext, LiveDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
    }

    private void recyclerView2() {
        //创建默认的GridLayoutManager
        mGridLayoutManager2 = new FullyGridLayoutManager(getContext(), 2);
        mGridLayoutManager2.setScrollEnabled(false);
        live_recycler_view2.setLayoutManager(mGridLayoutManager2);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        live_recycler_view2.setHasFixedSize(true);
        //创建并设置Adapter
        liveFragmentAdapter2 = new LiveFragmentAdapter2(bean.getActivity());
        live_recycler_view2.setAdapter(liveFragmentAdapter2);
        liveFragmentAdapter2.setOnItemClickListener(new LiveFragmentAdapter2.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("timeStatus", bean.getActivity().get(position).getTimeStatus() + "");
                intent.putExtra("activityId", bean.getActivity().get(position).getActivityid());
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.setClass(mContext, BookingDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
    }

    /**
     * 顶部ViewPager样式设置
     */
    public void banner() {
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
            }

        });
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent();
                switch (position) {
                    case 0:
                        if (ApplicationUtils.getInstance().loginBean == null) {
                            Intent intent2 = new Intent();
                            intent2.setClass(getContext(), WxLoginPage.class);
                            startActivity(intent2);
                            getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                            return;
                        }
                        intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        intent.putExtra("timeStatus", timeStatus[0] + "");
                        intent.putExtra("activityId", id[0]);
                        intent.setClass(getActivity(), BookingDetailsPage.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);

                        break;
                    case 1:
                        if (ApplicationUtils.getInstance().loginBean == null) {
                            Intent intent3 = new Intent();
                            intent3.setClass(getContext(), WxLoginPage.class);
                            startActivity(intent3);
                            getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                            return;
                        }
                        intent.putExtra("timeStatus", timeStatus[1] + "");
                        intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        intent.putExtra("activityId", id[1]);
                        intent.setClass(getActivity(), BookingDetailsPage.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);

                        break;
                    case 2:
                        if (ApplicationUtils.getInstance().loginBean == null) {
                            Intent intent4 = new Intent();
                            intent4.setClass(getContext(), WxLoginPage.class);
                            startActivity(intent4);
                            getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                            return;
                        }
                        intent.putExtra("timeStatus", timeStatus[2]);
                        intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        intent.putExtra("activityId", id[2] + "");
                        intent.setClass(getActivity(), BookingDetailsPage.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);

                        break;
                }
            }
        });
    }

    protected void enableDisableSwipeRefresh(boolean enable) {
        if (mRefreshLayout != null) {
//            setEnabled(enable)
            mRefreshLayout.setEnableRefresh(enable);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }
}
